import { sortTable, isFunction } from './utils'
export default {
	props: {
		data: {
			type: Array,
			default: () => []
		},
		loading: {
			type: Boolean,
			default: () => false
		},
		columns: {
			type: Array,
			default: () => []
		},

		id: {
			type: String,
			default: () => window.location.pathname
		},

		// 是否支持table排序
		isSortTable: {
			type: Boolean,
			default: false
		},

		// 渲染column前执行
		beforeColunm: {
			type: Function,
			default: undefined
		},
		tableHeight: {
			type: String | Number,
			default: 480
		}
	},

	mounted() {
		sortTable({
			start: this.isSortTable,
			onChange: () => {}
		})
	},

	methods: {
		_beforeColunm(columnProps) {
			const defaultProps = {
				minWidth: '150px',
				align: 'center',
				isShow: true,
				emptyText: '-', // 空时显示内容
				customRender: ({ row }) => {
					const val = row?.[columnProps.prop] || ''
					const texts = columnProps.texts
					let content = val
					if (texts) {
						content = texts[val]
					}
					if (content === 0) {
						content = '0'
					}
					return content || defaultProps.emptyText
				}
			}
			const mergeProps = Object.assign(defaultProps, columnProps)

			if (isFunction(this.beforeColunm)) {
				const newColumnProps = this.beforeColunm(mergeProps)
				// 返回false不显示当前列
				if (newColumnProps === false) {
					mergeProps.isShow = false
				}
				// 返回一个新对象
				if (typeof newColumnProps === 'object') {
					return newColumnProps
				}
			}
			return mergeProps
		}
	},

	render(h) {
		return (
			<el-table
				fit
				border
				highlight-current-row
				size='mini'
				class='dx-table'
				headerAlign='center'
				loading={this.loading}
				data={this.data}
				style='width: 100%'
				max-height={this.tableHeight}
			>
				{this.columns.map((column) => {
					const {
						prop,
						label,
						minWidth,
						align,
						customRender,
						header,
						isShow,
						width
					} = this._beforeColunm(column)
					if (isShow === false) {
						return null
					} else if (typeof isShow === 'function') {
						if (isShow() === false) return null
					}

					return (
						<el-table-column
							key={prop}
							resizable={false}
							prop={prop}
							label={label}
							minWidth={minWidth}
							width={width}
							align={align}
							sortable={false}
							scopedSlots={{ default: customRender, header }}
						/>
					)
				})}
			</el-table>
		)
	}
}
